﻿CREATE PROCEDURE [dbo].[CashRegisterDocDelete]
(--кассовый чек (розничная продажа)
	@Original_Id int,
	@Original_MD datetime
)
AS
DECLARE @strMsg nvarchar(500), @intErrCode int, @intRet int, @orgDocTypeId int
DECLARE @intLineId int, @datLineMD datetime, @strDocNumber varchar(20)
DECLARE @intCashRegisterShiftId int, @intCashRegisterId int

SET NOCOUNT ON
IF (@Original_Id Is Null) OR (@Original_MD Is Null) 
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

SELECT @orgDocTypeId = DocTypeId, @strDocNumber = DocNumber, 
@intCashRegisterShiftId = CashRegisterShiftId
FROM CA.Documents WHERE Id = @Original_Id AND MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 2, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF @orgDocTypeId <> 3
BEGIN
	SELECT @intErrCode = 3, 
	@strMsg = 'Неправильный тип документа!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF @intCashRegisterShiftId IS Null
BEGIN
	SELECT @intErrCode = 4, 
	@strMsg = 'Отсутствует идентификатор кассовой смены!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @intRet = NextDocNumber, @intCashRegisterId = R.Id
FROM CD.CashRegisters AS R INNER JOIN CD.CashRegisterShifts S
ON R.Id = S.CashRegisterId
WHERE S.Id = @intCashRegisterShiftId

IF @intRet IS Null
BEGIN
	SELECT @intErrCode = 5, 
	@strMsg = 'Неопределён следующий номер чека!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF @intRet <> cast(@strDocNumber as int) + 1
BEGIN
	SELECT @intErrCode = 6, 
	@strMsg = 'Удалить можно только последний чек!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

EXEC @intRet = dbo.CheckAllowUpdateDeleteForRecord @Original_Id
IF @intRet <> 0 RETURN @intRet

DECLARE DocLines CURSOR FAST_FORWARD FOR
SELECT Id, MD FROM CA.GoodsDocLines  WHERE DocId = @Original_Id

OPEN DocLines

FETCH NEXT FROM DocLines INTO @intLineId, @datLineMD
BEGIN TRAN

UPDATE CD.CashRegisters SET NextDocNumber = NextDocNumber -1 
WHERE Id = @intCashRegisterId

WHILE (@@FETCH_STATUS = 0)
BEGIN

		EXEC @intRet = dbo.CashRegisterLinesDelete @intLineId, @datLineMD
	
		SET @intErrCode = @@error
		IF @intErrCode <> 0
		BEGIN 
			IF @@trancount > 0 ROLLBACK TRANSACTION
			CLOSE DocLines
			DEALLOCATE DocLines
			RETURN @intErrCode
		END
		
		IF @intRet <> 0
		BEGIN 
			IF @@trancount > 0 ROLLBACK TRANSACTION
			CLOSE DocLines
			DEALLOCATE DocLines
			RETURN @intRet
		END
	
	FETCH NEXT FROM DocLines INTO @intLineId, @datLineMD
END

CLOSE DocLines
DEALLOCATE DocLines

	SET NOCOUNT OFF;
DELETE FROM [CA].[Documents] WHERE Id = @Original_Id

SET @intErrCode = @@error
IF @intErrCode <> 0
BEGIN 
	IF @@trancount > 0 ROLLBACK TRANSACTION
	RETURN @intErrCode
END

COMMIT TRAN

RETURN 0
